package com.aiwu.pop;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import androidx.appcompat.app.AlertDialog;

import com.aiwu.PrefsHelper;
import com.aiwu.ScreenEditActivity;
import com.aiwu.adapter.ScreenLayoutAdapter;
import com.aiwu.bean.ScreenConfig;
import com.aiwu.interfaces.ScreenLayoutListener;
import com.aiwu.library.App;
import com.aiwu.library.ui.pop.EditConfigNamePop;
import com.aiwu.library.util.DialogUtil;
import com.aiwu.library.util.DisplayUtil;
import com.aiwu.library.util.ToastUtil;

import org.citra.citra_emu.NativeLibrary;
import org.citra.citra_emu.R;
import org.citra.citra_emu.activities.EmulationActivity;
import org.citra.citra_emu.features.settings.model.IntSetting;
import org.citra.citra_emu.features.settings.model.Setting;
import org.citra.citra_emu.features.settings.model.SettingSection;
import org.citra.citra_emu.features.settings.model.Settings;
import org.citra.citra_emu.features.settings.utils.SettingsFile;
import org.citra.citra_emu.utils.EmulationMenuSettings;

import java.util.ArrayList;
import java.util.List;

/**
 * 屏幕布局
 */
public class SwitchScreenLayoutDialog extends AlertDialog implements View.OnClickListener, ScreenLayoutListener {
    private EmulationActivity activity;
    private FastSettingDialog fastSettingDialog;
    private View contentView;
    private ListView listView;
    private ScreenLayoutAdapter adapter;

    public static final int[] LAYOUT_OPTIONS = new int[]{EmulationMenuSettings.LayoutOption_MobileLandscape,
            EmulationMenuSettings.LayoutOption_MobilePortrait,
            EmulationMenuSettings.LayoutOption_SingleScreen,
            EmulationMenuSettings.LayoutOption_SideScreen};

    public SwitchScreenLayoutDialog(EmulationActivity context, FastSettingDialog fastSettingDialog) {
        super(context, R.style.AiWuDialog);
        this.activity = context;
        this.fastSettingDialog = fastSettingDialog;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        activity.setScreenLayoutListener(this);
    }

    @Override
    public void dismiss() {
        activity.setScreenLayoutListener(null);
        super.dismiss();
    }

    private void init() {
        contentView = View.inflate(getContext(), R.layout.dialog_switch_screen_layout, null);
        setContentView(contentView);
        setCancelable(true);
        setCanceledOnTouchOutside(true);
        initView();
        initData();
    }

    private void initView() {
        findViewById(R.id.btn_insert).setOnClickListener(this);
        listView = findViewById(R.id.listView);
        listView.setEmptyView(findViewById(R.id.emptyView));
    }

    private void initData() {
        adapter = new ScreenLayoutAdapter();
        listView.setAdapter(adapter);
        adapter.setBtnClickListener(new ScreenLayoutAdapter.BtnClickListener() {
            @Override
            public void nameBtnClick(int id, int position) {
                showRenameTip(id, position);
            }

            @Override
            public void useBtnClick(int id, int position) {
                useConfig(id, position);
            }

            @Override
            public void copyBtnClick(int id, int position) {
                copyConfig(position);
            }

            @Override
            public void editBtnClick(int id, int position) {
                ScreenEditActivity.launch(activity, id, false);
            }

            @Override
            public void deleteBtnClick(int id, int position) {
                showDeleteTip(id, position);
            }
        });
        refreshData();
    }

    private void refreshData() {
        if (adapter != null)
            adapter.setData(getConfigList());
    }

    /**
     * 使用某个配置
     *
     * @param id
     */
    private void useConfig(int id, int position) {
        if (adapter == null || adapter.getData() == null) {
            return;
        }
        PrefsHelper.getInstance().setLastScreenConfigId(id);
        ScreenConfig config = adapter.getData().get(position);
        changeLayout(id, config);
        for (ScreenConfig itemBean : adapter.getData()) {
            itemBean.setUsing(itemBean.getId() == id);
        }
        adapter.notifyDataSetChanged();
    }

    private void useConfig(int id) {
        PrefsHelper.getInstance().setLastScreenConfigId(id);
        ScreenConfig config = PrefsHelper.getInstance().getScreenConfig(id);
        changeLayout(id, config);
    }

    /**
     * 改变模拟器布局
     *
     * @param config
     */
    private void changeLayout(int id, ScreenConfig config) {
        if (config == null) {
            return;
        }
        String[] keys = new String[]{SettingsFile.KEY_CUSTOM_LAYOUT,
                SettingsFile.KEY_CUSTOM_TOP_LEFT, SettingsFile.KEY_CUSTOM_TOP_TOP, SettingsFile.KEY_CUSTOM_TOP_RIGHT, SettingsFile.KEY_CUSTOM_TOP_BOTTOM,
                SettingsFile.KEY_CUSTOM_BOTTOM_LEFT, SettingsFile.KEY_CUSTOM_BOTTOM_TOP, SettingsFile.KEY_CUSTOM_BOTTOM_RIGHT, SettingsFile.KEY_CUSTOM_BOTTOM_BOTTOM};
        if (config.isCustom()) {
            int[] values = new int[]{1, config.getTopLeft(), config.getTopTop(), config.getTopRight(), config.getTopBottom(),
                    config.getBottomLeft(), config.getBottomTop(), config.getBottomRight(), config.getBottomBottom()};
            changeCustomValue(keys, values);
            NativeLibrary.NotifyOrientationChange(EmulationMenuSettings.getLandscapeScreenLayout(), activity.getWindowManager().getDefaultDisplay().getRotation());
        } else {
            int[] values = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0};
            changeCustomValue(keys, values);
            changeScreenOrientation(id, activity.getWindowManager().getDefaultDisplay().getRotation());
        }
    }

    private void changeCustomValue(String[] keys, int[] values) {
        Settings mSettings = fastSettingDialog.getSettings();
        for (int i = 0; i < keys.length; i++) {
            String key = keys[i];
            int value = values[i];
            SettingSection rendererSection = mSettings.getSection(Settings.SECTION_LAYOUT);
            Setting customLayout = rendererSection.getSetting(key);
            IntSetting setting = FastSettingDialog.setSelectedValue(value, customLayout, key, Settings.SECTION_LAYOUT);
            if (setting != null) {
                rendererSection.putSetting(setting);
            }
        }
        mSettings.saveSettings(null);
        NativeLibrary.ReloadSettings();
    }

    /**
     * 添加新配置
     *
     * @return
     */
    private void insertConfig() {
        //找到新配置的id
        int newConfigId = -1;
        int startId, endId;
        if (DisplayUtil.isLandscape()) {
            startId = PrefsHelper.SCREEN_CONFIG_ID_LANDSCAPE_START;
            endId = PrefsHelper.SCREEN_CONFIG_ID_LANDSCAPE_END;
        } else {
            startId = PrefsHelper.SCREEN_CONFIG_ID_PORTRAIT_START;
            endId = PrefsHelper.SCREEN_CONFIG_ID_PORTRAIT_END;
        }
        for (int i = startId; i <= endId; i++) {
            boolean repeat = false;
            for (ScreenConfig item : adapter.getData()) {
                if (item.getId() == i) {
                    repeat = true;
                    break;
                }
            }
            if (!repeat) {
                newConfigId = i;
                break;
            }
        }
        if (newConfigId == -1) {
            ToastUtil.toast("配置已满,新建配置失败");
            return;
        }
        ScreenEditActivity.launch(activity, newConfigId, true);
    }

    /**
     * 复制配置
     *
     * @return 是否复制成功
     */
    private boolean copyConfig(int position) {
        final ScreenConfig itemBean = adapter.getItem(position);
        if (itemBean == null) {
            ToastUtil.toast(R.string.copy_config_error);
            return false;
        }
        int newConfigId = -1;
        int startId, endId;
        if (DisplayUtil.isLandscape()) {
            startId = PrefsHelper.SCREEN_CONFIG_ID_LANDSCAPE_START;
            endId = PrefsHelper.SCREEN_CONFIG_ID_LANDSCAPE_END;
        } else {
            startId = PrefsHelper.SCREEN_CONFIG_ID_PORTRAIT_START;
            endId = PrefsHelper.SCREEN_CONFIG_ID_PORTRAIT_END;
        }
        for (int i = startId; i <= endId; i++) {
            boolean repeat = false;
            for (ScreenConfig item : adapter.getData()) {
                if (item.getId() == i) {
                    repeat = true;
                    break;
                }
            }
            if (!repeat) {
                newConfigId = i;
                break;
            }
        }
        if (newConfigId == -1) {
            ToastUtil.toast("配置已满,新建配置失败");
            return false;
        }
        ScreenConfig newConfig = new ScreenConfig(true, false, newConfigId, itemBean.getName() + "-副本",
                itemBean.getTopLeft(), itemBean.getTopTop(), itemBean.getTopRight(), itemBean.getTopBottom(),
                itemBean.getBottomLeft(), itemBean.getBottomTop(), itemBean.getBottomRight(), itemBean.getBottomBottom());
        //添加新配置
        PrefsHelper.getInstance().saveNewScreenConfig(newConfigId, newConfig.getName(),
                newConfig.getTopLeft(), newConfig.getTopTop(), newConfig.getTopRight(), newConfig.getTopBottom(),
                newConfig.getBottomLeft(), newConfig.getBottomTop(), newConfig.getBottomRight(), newConfig.getBottomBottom());
        adapter.addData(newConfig);
        return true;
    }

    private List<ScreenConfig> getConfigList() {
        List<ScreenConfig> list = new ArrayList<>();
        int startId, endId;
        if (DisplayUtil.isLandscape()) {
            //横屏要加上4个配置
            for (int type : LAYOUT_OPTIONS) {
                ScreenConfig config = createConfigByType(type);
                list.add(config);
            }
            startId = PrefsHelper.SCREEN_CONFIG_ID_LANDSCAPE_START;
            endId = PrefsHelper.SCREEN_CONFIG_ID_LANDSCAPE_END;
        } else {
            //横屏要加上1个配置
            ScreenConfig config = createConfigByType(LAYOUT_OPTIONS[0]);
            list.add(config);
            startId = PrefsHelper.SCREEN_CONFIG_ID_PORTRAIT_START;
            endId = PrefsHelper.SCREEN_CONFIG_ID_PORTRAIT_END;
        }
        for (int i = startId; i <= endId; i++) {
            ScreenConfig config = PrefsHelper.getInstance().getScreenConfig(i);
            if (config == null) {
                continue;
            }
            list.add(config);
        }
        return list;
    }

    /**
     * 构建系统的几个配置
     *
     * @param layoutOptionType
     * @return
     */
    public static ScreenConfig createConfigByType(int layoutOptionType) {
        ScreenConfig config = new ScreenConfig();
        config.setId(layoutOptionType);
        config.setUsing(layoutOptionType == PrefsHelper.getInstance().getLastScreenConfigId());
        config.setCustom(false);
        String name = "";
        switch (layoutOptionType) {
            case EmulationMenuSettings.LayoutOption_MobileLandscape:
                name = App.getContext().getString(R.string.emulation_screen_layout_landscape);
                break;
            case EmulationMenuSettings.LayoutOption_MobilePortrait:
                name = App.getContext().getString(R.string.emulation_screen_layout_portrait);
                break;
            case EmulationMenuSettings.LayoutOption_SingleScreen:
                name = App.getContext().getString(R.string.emulation_screen_layout_single);
                break;
            case EmulationMenuSettings.LayoutOption_SideScreen:
                name = App.getContext().getString(R.string.emulation_screen_layout_sidebyside);
                break;
        }
        config.setName(name);
        return config;
    }

    private void showRenameTip(final int id, final int position) {
        final ScreenConfig itemBean = adapter.getItem(position);
        if (itemBean == null) {
            return;
        }
        final EditConfigNamePop namePop = new EditConfigNamePop(getContext()) {
            @Override
            protected void initView() {
                final EditText et = findViewById(R.id.et);
                et.setText(itemBean.getName());
                et.setSelection(itemBean.getName().length());
                Button btnCancel = findViewById(R.id.btn_cancel);
                Button btnConfirm = findViewById(R.id.btn_confirm);
                btnCancel.setOnClickListener(v -> dismiss());
                btnConfirm.setOnClickListener(v -> {
                    String newName = et.getText().toString();
                    if (TextUtils.isEmpty(newName)) {
                        ToastUtil.toast(R.string.config_name_empty);
                        return;
                    }
                    dismiss();
                    PrefsHelper.getInstance().editScreenConfigName(id, newName);
                    itemBean.setName(newName);
                    adapter.notifyDataSetChanged();
                });
            }
        };
        namePop.show();
    }

    private void showDeleteTip(final int id, final int position) {
        DialogUtil.showTip(getContext(), R.string.delete_config_tip, v -> {
            PrefsHelper.getInstance().removeScreenConfig(id);
            adapter.removeData(position);
        }, null);
    }

    public static void changeScreenOrientation(int layoutOption, int rotation) {
        NativeLibrary.NotifyOrientationChange(layoutOption, rotation);
        EmulationMenuSettings.setLandscapeScreenLayout(layoutOption);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_insert:
                insertConfig();
                break;
        }
    }

    @Override
    public void show() {
        super.show();
        DialogUtil.setDialog(this, 0.6f, 0.9f, 0.8f, 0.6f);
    }

    @Override
    public void layoutInserted(int screenLayoutId) {
        useConfig(screenLayoutId);
        refreshData();
    }

    @Override
    public void layoutEdited(int screenLayoutId) {
        useConfig(screenLayoutId);
        refreshData();
    }
}
